<template>
  <div class="user-sales-chart">
    <div class="chart-header">
      <h2 class="chart-title">{{ title }}</h2>
      <div class="chart-controls">
        <div class="date-range-selector">
          <span 
            v-for="option in dateRangeOptions" 
            :key="option.value"
            :class="['date-range-option', { active: selectedRange === option.value }]"
            @click="changeRange(option.value)"
          >
            {{ option.label }}
          </span>
        </div>
      </div>
    </div>
    
    <div class="chart-container">
      <div v-if="loading" class="chart-loading">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>
      <div v-else-if="error" class="chart-error">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <circle cx="12" cy="12" r="10"></circle>
          <line x1="12" y1="8" x2="12" y2="12"></line>
          <line x1="12" y1="16" x2="12.01" y2="16"></line>
        </svg>
        <span>{{ error }}</span>
      </div>
      <div v-else class="chart-content">
        <div ref="salesChartRef" class="sales-chart"></div>
      </div>
    </div>
    
    <div class="chart-summary">
      <div class="summary-item">
        <div class="summary-label">总销售额</div>
        <div class="summary-value">¥{{ formattedTotalSales }}</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">总佣金</div>
        <div class="summary-value">¥{{ formattedTotalCommission }}</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">佣金比率</div>
        <div class="summary-value">{{ userData?.commissionRate }}%</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, nextTick, onBeforeUnmount } from 'vue';
import { generateUserSalesData } from '@/utils/adminMock';
// 如果项目中有Apache ECharts，则使用以下引入方式
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent, GridComponent, ToolboxComponent, DataZoomComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
  LineChart,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  DataZoomComponent,
  CanvasRenderer
]);

const props = defineProps({
  userId: {
    type: String,
    required: true
  },
  title: {
    type: String,
    default: '用户销售数据'
  }
});

const salesChartRef = ref<HTMLElement | null>(null);
const salesChart = ref<echarts.ECharts | null>(null);
const loading = ref(true);
const error = ref('');
const userData = ref<any>(null);
const selectedRange = ref(30);
const chartInitialized = ref(false);

const dateRangeOptions = [
  { value: 7, label: '7天' },
  { value: 14, label: '14天' },
  { value: 30, label: '30天' },
  { value: 90, label: '90天' }
];

const formattedTotalSales = computed(() => {
  return userData.value?.totalSales?.toLocaleString() || '0';
});

const formattedTotalCommission = computed(() => {
  return userData.value?.totalCommission?.toLocaleString() || '0';
});

// 加载销售数据
const loadSalesData = async () => {
  try {
    loading.value = true;
    error.value = '';
    // 在实际项目中，这里应该调用API获取数据
    // 这里使用mock数据模拟
    const data = generateUserSalesData(props.userId, selectedRange.value);
    userData.value = data;
    loading.value = false;
    
    // 数据加载完成后初始化或更新图表
    await nextTick();
    setTimeout(() => {
      initOrUpdateChart();
    }, 100); // 添加延迟以确保DOM已完全渲染
  } catch (err) {
    loading.value = false;
    error.value = '加载数据失败，请稍后重试';
    console.error('加载销售数据失败:', err);
  }
};

// 改变时间范围
const changeRange = (days: number) => {
  selectedRange.value = days;
  loadSalesData();
};

// 初始化或更新图表
const initOrUpdateChart = () => {
  if (!salesChartRef.value) {
    console.error('Chart DOM element is not available');
    return;
  }
  
  try {
    // 如果图表实例存在，先销毁
    if (chartInitialized.value && salesChart.value) {
      salesChart.value.dispose();
    }
    
    // 确保容器有明确的尺寸
    const container = salesChartRef.value;
    if (container.clientWidth === 0 || container.clientHeight === 0) {
      console.warn('Chart container size is zero, setting default size');
      container.style.width = '100%';
      container.style.height = '400px';
    }
    
    // 初始化图表
    salesChart.value = echarts.init(container);
    chartInitialized.value = true;
    
    const salesData = userData.value?.salesData || [];
    const dates = salesData.map((item: any) => item.date);
    const sales = salesData.map((item: any) => item.sales);
    const commissions = salesData.map((item: any) => item.commission);
    
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: function(params: any) {
          const date = params[0].axisValue;
          let html = `<div style="margin: 0 0 5px; font-weight: bold;">${date}</div>`;
          
          params.forEach((param: any) => {
            const color = param.color;
            const marker = `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color};"></span>`;
            const name = param.seriesName;
            const value = param.value;
            html += `<div style="margin: 3px 0">${marker} ${name}: ¥${value.toLocaleString()}</div>`;
          });
          
          return html;
        }
      },
      legend: {
        data: ['销售额', '佣金'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '60px',
        top: '30px',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: { title: '保存为图片' }
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates,
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisLabel: {
          color: '#666',
          formatter: function(value: string) {
            // 简化日期显示
            return value.split('-').slice(1).join('-');
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#666',
          formatter: function(value: number) {
            return '¥' + value.toLocaleString();
          }
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      series: [
        {
          name: '销售额',
          type: 'line',
          data: sales,
          symbolSize: 6,
          itemStyle: {
            color: '#409EFF'
          },
          lineStyle: {
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          },
          smooth: true
        },
        {
          name: '佣金',
          type: 'line',
          data: commissions,
          symbolSize: 6,
          itemStyle: {
            color: '#67C23A'
          },
          lineStyle: {
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
            ])
          },
          smooth: true
        }
      ]
    };
    
    salesChart.value.setOption(option);
    
    // 添加窗口大小变化的响应
    window.addEventListener('resize', handleResize);
  } catch (err) {
    console.error('初始化或更新图表失败:', err);
    error.value = '图表初始化失败，请刷新页面重试';
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (salesChart.value) {
    salesChart.value.resize();
  }
};

// 加载数据
onMounted(() => {
  loadSalesData();
});

// 监听用户ID变化，重新加载数据
watch(() => props.userId, () => {
  loadSalesData();
});

// 组件卸载时清理资源
onBeforeUnmount(() => {
  if (salesChart.value) {
    salesChart.value.dispose();
    window.removeEventListener('resize', handleResize);
  }
});
</script>

<style scoped lang="scss">
.user-sales-chart {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .chart-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
    
    .chart-controls {
      display: flex;
      gap: 10px;
    }
    
    .date-range-selector {
      display: flex;
      gap: 2px;
      background-color: #f5f7fa;
      border-radius: 6px;
      overflow: hidden;
      
      .date-range-option {
        padding: 6px 12px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover {
          background-color: #ebeef5;
        }
        
        &.active {
          background-color: #409eff;
          color: #fff;
        }
      }
    }
  }
  
  .chart-container {
    position: relative;
    min-height: 400px;
    
    .chart-loading, .chart-error {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: rgba(255, 255, 255, 0.7);
      z-index: 10;
    }
    
    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(64, 158, 255, 0.2);
      border-radius: 50%;
      border-top-color: #409eff;
      animation: spin 1s ease-in-out infinite;
      margin-bottom: 10px;
    }
    
    .chart-error {
      color: #f56c6c;
      
      svg {
        margin-bottom: 10px;
        stroke: #f56c6c;
      }
    }
    
    .sales-chart {
      width: 100%;
      height: 400px;
    }
  }
  
  .chart-summary {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
    
    .summary-item {
      text-align: center;
      
      .summary-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }
      
      .summary-value {
        font-size: 22px;
        font-weight: 600;
        color: #333;
      }
    }
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .user-sales-chart {
    .chart-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
    }
    
    .chart-summary {
      flex-direction: column;
      gap: 15px;
      
      .summary-item {
        display: flex;
        justify-content: space-between;
        text-align: left;
        
        .summary-value {
          font-size: 18px;
        }
      }
    }
  }
}
</style> 